# -*- coding = utf-8 -*-
# Time : 2021/2/9
# Author : fxg
# File : 抢劵.py

from datetime import datetime
import io
import json
import math
import os
import random
import re
import threading
import time
import requests
from PIL import Image
from requests.cookies import RequestsCookieJar

session = requests.session()
session.verify = None
session.headers["Accept"] = "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8"
session.headers["Accept-Encoding"] = "gzip, deflate, br"
session.headers["Accept-Language"] = "zh-CN,zh;q=0.9"
session.headers["Connection"] = "keep-alive"
session.headers["referer"] = "https://passport.jd.com/"


ti_time = '2024-04-10 09:59:59.599889'
switch = True

T = None


def get_time():
    """"
    获取时间
    """
    start_time = datetime.now()
    url = 'https://www.jishirili.com/time.asp'
    response = requests.get(url, verify=False)
    response.close()
    if response.status_code == 200:
        timestamp_ms = response.json()
        # 将毫秒转换为秒
        timestamp_sec = timestamp_ms / 1000

        # 将时间戳转换为日期时间对象
        datetime_obj = datetime.fromtimestamp(timestamp_sec)
        end_time = datetime.now()
        execution_time = (end_time - start_time)
        return execution_time+datetime_obj
    else:
        return None


def start_thread():
    global T
    T = threading.Thread(target=wait_cahe)  # 多线程
    T.daemon = True  # 线程守护，即主进程结束后，此线程也结束。否则主进程结束子进程不结束
    T.start()  # 启动
    T.join()


def wait_cahe():
    global switch
    switch = True
    now = get_time()
    ti = datetime.strptime(
        ti_time, '%Y-%m-%d %H:%M:%S.%f')
    while switch:
        start_time = datetime.now()
        if now < ti:
            timer = '当前时间 {}'.format(now)
            print(timer, end='\r')
            time.sleep(0.01)
            end_time = datetime.now()
            execution_time = (end_time - start_time)
            now = execution_time+now
        else:
            switch = False
            timer = '开始抢劵 {}'.format(now)
            print(timer)
            # 创建并发执行的线程
            threads = []
            for _ in range(3):
                t = threading.Thread(target=qg)
                threads.append(t)
                t.start()
                time.sleep(0.3)

            # 等待所有线程执行完毕
            for t in threads:
                t.join()
# 获取登录二维码


def get_login_image():

    millis = int(round(time.time() * 1000))
    # 获取验证码图片
    img_url = 'https://qr.m.jd.com/show?appid=133&size=147&t=()'.format(millis)

    response = session.get(img_url)
    response.close()
    # 获取二维码进行登录
    with open(r'JD.png', 'wb') as f:
        f.write(response.content)

    image = Image.open(io.BytesIO(response.content))
    image = image.convert('RGBA')
    image.show()
    while True:
        html_set_cookie = requests.utils.dict_from_cookiejar(session.cookies)
        session.cookies['wlfstk_smdl'] = html_set_cookie['wlfstk_smdl']
        session.cookies['QRCodeKey'] = html_set_cookie['QRCodeKey']
        millis = int(round(time.time() * 1000))
        num = random.random() * 10000000
        # 轮询扫码状态
        check_url = 'https://qr.m.jd.com/check?callback=jQuery{}&appid=133&token={}&_={}'.format(math.floor(num),
                                                                                                 html_set_cookie[
            'wlfstk_smdl'],
            millis)
        response = session.get(check_url)
        response.close()
        print(response.text)
        if '200' in response.text:
            print('登录成功')
            break
        if '201' not in response.text:
            print('二维码过期')
            continue

        time.sleep(3)
    # 获取登录cookies
    ticket = re.findall('"ticket" : "(.*?)"', response.text)
    login_url = 'https://passport.jd.com/uc/qrCodeTicketValidation?t={}&ReturnUrl=http://jingyin.jd.com'.format(
        ticket)

    response = session.get(login_url)
    response.close()
    if 'https://jingyin.jd.com/' in response.text:
        print('登录成功')
    html_set_cookie = requests.utils.dict_from_cookiejar(session.cookies)
    session.cookies['TrackID'] = html_set_cookie['TrackID']
    session.cookies['thor'] = html_set_cookie['thor']
    session.cookies['pinId'] = html_set_cookie['pinId']
    session.cookies['pin'] = html_set_cookie['pin']
    session.cookies['unick'] = html_set_cookie['unick']
    session.cookies['ceshi3.com'] = html_set_cookie['ceshi3.com']
    session.cookies['_tp'] = html_set_cookie['_tp']
    session.cookies['logining'] = html_set_cookie['logining']
    session.cookies['_pst'] = html_set_cookie['_pst']

    cookies = ''
    for item in session.cookies:
        cookies += item.name+'='+item.value+";"
    return cookies


def qg():
    url = "https://api.m.jd.com/client.action?functionId=newBabelAwardCollection&body=%7B%22activityId%22%3A%222qpYiUaTE23fhQsUMrjzFbYFYa1o%22%2C%22gridInfo%22%3A%22%22%2C%22transParam%22%3A%22%7B%5C%22bsessionId%5C%22%3A%5C%2245c780ba-6742-47d8-b579-a8d5ee3b0239%5C%22%2C%5C%22babelChannel%5C%22%3A%5C%22%5C%22%2C%5C%22actId%5C%22%3A%5C%2201624311%5C%22%2C%5C%22enActId%5C%22%3A%5C%222qpYiUaTE23fhQsUMrjzFbYFYa1o%5C%22%2C%5C%22pageId%5C%22%3A%5C%224774363%5C%22%2C%5C%22encryptCouponFlag%5C%22%3A%5C%221%5C%22%2C%5C%22requestChannel%5C%22%3A%5C%22h5%5C%22%2C%5C%22jdAtHomePage%5C%22%3A%5C%220%5C%22%2C%5C%22utmFlag%5C%22%3A%5C%220%5C%22%2C%5C%22locType%5C%22%3A%5C%221%5C%22%7D%22%2C%22scene%22%3A%221%22%2C%22args%22%3A%22key%3D7353C21C5A6D5F31DB8E539DD52E3759097B051D11DBC8C721628079189D2711243993A93C6A9EFBB63E1645B14AA1D7_bingo%2CroleId%3D35C661551EA71858493F611380FAABD07DDDAD6A79F96AB397BA74D35089C766C2F2CB9E7AE5A923B6854D2F5733CB858BF483712F544BB74153660C8DA4FCF253CD4A3EAED088939412A1E974728B52459FCCF8A22C0DDF3499DCD4647CE5F14D235D46638F60703DF9586D58E33D07C1C68010051C0CA6722058D3D6C521250FA1E3B70DD0326C792F791767B7881FE12E54DE66ADF7BBE2883F7021F8BC83_bingo%22%2C%22log%22%3A%221%2C1%22%7D&client=wh5"
    response = session.get(url)
    response.close()
    print(response.json())


def main():
    global ti_time
    print(ti_time)
    file_path = "cookies.txt"
    if os.path.exists(file_path):
        with open("cookies.txt", "r") as f:
            cookies_data = json.load(f)
        # 创建一个空的 cookie jar
        cookies_jar = RequestsCookieJar()

        # 将从文件中加载的 cookies 数据添加到 cookie jar 中
        for cookie_str in cookies_data.split(";"):
            if cookie_str.strip():
                cookie_name, cookie_value = cookie_str.split("=", 1)
                cookies_jar.set(cookie_name, cookie_value)

        # 现在，cookies_jar 包含了从文件中读取的 cookies 数据
        # 将 cookies 添加到 session 中
        session.cookies.update(cookies_jar)
        start_thread()
    else:
        # 登录
        cookies = get_login_image()
        # 将 cookies 写入文件
        with open(file_path, "w") as f:
            json.dump(cookies, f)
        start_thread()


if __name__ == '__main__':
    main()
